/**
 *       Copyright (c) 2011 Lukas Zaruba
 * 
 *   This file is part of ParPortTester
 *
 *   ParPortTester is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   ParPortTester is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with ParPortTester. If not, see <http://www.gnu.org/licenses/>.
 */


package net.zarubsys.parporttester;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

/**
 * @author  &lt;A HREF=&quot;mailto:lukas.zaruba@gmail.com&quot;&gt;Lukas Zaruba&lt;/A&gt; zarubsys.net
 */
public class Application implements IApplication {

	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd-HHmm");
	
	public Object start(IApplicationContext context) throws Exception {
		Display display = PlatformUI.createDisplay();
		try {
			initLogging();
			Logger.getLogger("").info("Application started...");
			int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART)
				return IApplication.EXIT_RESTART;
			else
				return IApplication.EXIT_OK;
		} finally {
			display.dispose();
		}
		
	}

	private void initLogging() {
		Logger logger = Logger.getLogger("");
		logger.setLevel(Level.INFO);
		String logDir = Platform.getInstanceLocation().getURL().getFile() + "logs/";
		File dir = new File(logDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		String logPath = logDir + "parPortTesterLog-" + SDF.format(new Date()) + ".log";
		FileHandler fileTxt = null;
		try {
			fileTxt = new FileHandler(logPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		SimpleFormatter formatterTxt = new SimpleFormatter();
		fileTxt.setFormatter(formatterTxt);
		logger.addHandler(fileTxt);
	}

	public void stop() {
		Logger.getLogger("").info("Application terminated...");
		final IWorkbench workbench = PlatformUI.getWorkbench();
		if (workbench == null)
			return;
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
}
